<template>
  <page-meta :root-font-size="fontSize + 'px'"></page-meta>

  <view class="page-container">
    <CustomHeader :title="pageModule.title" :border-line="false" />

    <view class="scene-container" :style="{ top: height }">

      <view class="progress-content">
        <view class="outside">
          <view class="inside">
            <text class="text">正确率</text>
            <text class="text">{{ pageModule.progress }}</text>
          </view>
        </view>
      </view>

      <view class="total-time">
        <text v-show="pageModule.totalTime">总用时 : {{ pageModule.totalTime }}s</text>
      </view>


      <view class="result-content">
        <view class="title">自检结果</view>
        <view class="body">
          <template v-for="(parent) in pageModule.pageData" :key="parent.type">
            <view class="item">
              <view class="title">{{ parent.title }}</view>
              <view class="content">
                <template v-for="(child) in parent.result" :key="child.topic_id">
                  <view @click="pageModule.handleToDetail(parent.type, child.topic_id)"
                    :class="['base', child.className]">
                    <text>{{ child.idx }}</text>
                  </view>
                </template>
              </view>
            </view>
          </template>
        </view>
        <view class="mark"></view>
      </view>
    </view>

    <view class="button-content">
      <view v-show="+props.is_not_root" class="button" @click="pageModule.handleOpenModal">
        重新开始
      </view>
      <view v-show="!(+props.is_not_root)" class="button" @click="getFinishResult">
        毕业档案
        <image class="button-right-icon" src="https://rwstatic.tentons.cn/web/Lesson/images/button-right-icon.png" />
      </view>
    </view>

    <CwCommon @modal-confirm="pageModule.onSubmitConfirm"></CwCommon>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref, useCssModule } from "vue";
import { rootFontSize, getFormatTime, util } from "@/utils/util";
import CustomHeader from "@/components/customHeader.vue";
import API from "@/api";
import { Course, CoursePageEnum } from './index';
import { useStore } from "vuex";
import { getAnyApp } from "@/common/hooks";

enum ResultEnum {
  INFO,
  SUCCESS,
  ERROR
}

interface Props {
  is_not_root: string | number;
}

const store = useStore();

const { Cheese, CHEESE } = getAnyApp();

const props = withDefaults(defineProps<Props>(), {
  is_not_root: 2,
});

const fontSize = rootFontSize();

const height = ref(getApp().globalData!.pageTop);

const STATUS_CSS_MODULE = useCssModule('status');

/**
 * 页面数据模块
 */
const pageModule = reactive({
  pageData: [] as any[],
  title: '随课自检',
  progress: '0%',
  totalTime: '',
  type: '',
  async init(callback?: Function) {
    try {
      const resultData: any = await API.getCourseAnswerResult({ section_id: Course.sectionId });
      resultData?.title && (this.title = resultData.title);
      resultData?.true_ratio && (this.progress = resultData.true_ratio);
      this.totalTime = getFormatTime((resultData.use_time ?? 0), 'hh-mm-ss', 'h-min', true);
      this.pageData = this.formatData(resultData?.answerSort || []);
    } catch (e) {
      console.error(e);
    } finally {
      callback && callback();
    }
  },
  formatData(data: any[]) {
    data.forEach((item) => {
      if (item?.result && item.result.length) {
        fun(item.result);
      }
    });
    function fun(list: any[]) {
      for (let i = 0; i < list.length; i++) {
        switch (list[i].is_true) {
          case ResultEnum.INFO:
            list[i].className = STATUS_CSS_MODULE.info;
            break;
          case ResultEnum.SUCCESS:
            list[i].className = STATUS_CSS_MODULE.success;
            break;
          case ResultEnum.ERROR:
            list[i].className = STATUS_CSS_MODULE.error;
            break;
        }
      }
    }
    return data;
  },
  handleToDetail(type: CoursePageEnum, topic_id: number) {
    let url = '';
    switch (type) {
      case CoursePageEnum.LISTEN:
        url = CHEESE.Router.Home.selfListeningAnalysis;
        break;
      case CoursePageEnum.GAP:
        url = CHEESE.Router.Home.selfGapFillingAnalysis;
        break;
    }
    CHEESE.Router.to({
      url,
      params: {
        topic_id,
        section_id: Course.sectionId
      }
    });
  },
  handleOpenModal() {
    util.showModal({
      isShowModal: true,
      title: "重新开始将会重置上次进度哦, 确定要重新开始吗?",
      cancelBtnText: '取消',
      confirmBtnText: '确认'
    });
  },
  async onSubmitConfirm() {
    try {
      await API.setCourseAnswerReset({ section_id: Course.sectionId });
      CHEESE.Router.redirectTo({
        url: Course.data[CoursePageEnum.LISTEN].sourceUrl,
      });
    } catch (e) {
      console.error(e);
    }
  }
});

(() => {
  pageModule.init();
})();

const getFinishResult = async () => {
  const course_id = store.state.courseId;

  const result = await API.finishResult({ course_id }) as any;
  result.dailyGpa.forEach((item: { day_num: number; }, index: number) => {
    if (item.day_num === -1) {
      result.dailyGpa.splice(index, 1);
    }
  });
  const temp = Object.assign(result, Cheese.User?.USERINFO, {
    day_num: 4,
    course_id: course_id,
  });

  uni.navigateTo({
    url: `/pages/lowPricedCourse/situationalDialog/shareDiploma/index?data=${encodeURIComponent(JSON.stringify(temp))}`,
  });
}
</script>

<style scoped lang="scss">
@mixin fontStyle($size) {
  font-size: #{ $size }rem;
  font-family: xiaolai;
  color: $uni-text-color;
}

.page-container {
  width: 100vw;
  height: 100vh;
  background-color: #F9EEDC;

  .scene-container {
    width: 37.5rem;
    position: absolute;
    bottom: 0;
    left: 50%;
    padding: 0 20px;
    transform: translateX(-50%);
    box-sizing: border-box;
    overflow-y: auto;
    padding-bottom: 10rem;
  }

  .progress-content {
    padding: 3rem 20px 0 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 3rem;

    .outside {
      height: 16.6rem;
      width: 16.6rem;
      box-shadow: 0 0 0 1rem #FEE1AD;
      border: 0.4rem solid #FFD388;
      border-radius: 50%;
      box-sizing: border-box;
    }

    .inside {
      border: 0.5rem solid #fff;
      background: #FFD388;
      height: 100%;
      width: 100%;
      border-radius: 50%;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .text {
        &:nth-child(1) {
          @include fontStyle(1.7);
        }

        &:nth-child(2) {
          @include fontStyle(3.8);
          font-family: baloo;
        }
      }
    }
  }

  .total-time {
    @include fontStyle(1.7);
    height: 2rem;
    text-align: center;
    margin-bottom: 2.8rem;
  }

  .button-content {
    @include fontStyle(1.7);
    position: fixed;
    bottom: calc(2.5rem + constant(safe-area-inset-bottom));
    bottom: calc(2.5rem + env(safe-area-inset-bottom));
    left: 50%;
    transform: translate(-50%);
    z-index: 999;

    .button {
      height: 5rem;
      line-height: 5rem;
      text-align: center;
      width: 31.5rem;
      box-sizing: border-box;
      border: 0.2rem solid $uni-btn-border;
      background-color: $uni-btn-prime;
      border-radius: 1rem;

      &:nth-child(1) {
        margin-bottom: 1.2rem;
      }

      .button-right-icon {
        width: 1.2rem;
        height: 1.2rem;
      }
    }
  }

  .result-content {
    position: relative;
    margin-top: 1.5rem;
    padding-top: 2rem;
    border-image-slice: 27 27 27 27 fill;
    border-image-width: 2rem 2rem 2rem 2rem;
    border-image-outset: 0 0 0 0;
    border-image-repeat: stretch stretch;
    border-style: solid;
    border-image-source: url("https://rwstatic.tentons.cn/web/Lesson/images/sentence-wrapper.png");

    >.title {
      @include fontStyle(1.7);
      display: flex;
      align-items: center;
      justify-content: center;
      width: 7.5rem;
      height: 1.8rem;
      margin: 0 auto 1.8rem;
      background-image: url("https://rwstatic.tentons.cn/web/Lesson/images/sentence-text.png");
      background-size: contain;
      background-repeat: no-repeat;
    }

    .mark {
      position: absolute;
      width: 4.2rem;
      height: 4.2rem;
      top: -1.4rem;
      left: 6.5rem;
      background-image: url("https://rwstatic.tentons.cn/web/Lesson/images/sentence-tag.png");
      background-size: contain;
      background-repeat: no-repeat;
    }

    .body {
      padding: 0 3.2rem;
      margin-bottom: 2.8rem;

      .item {
        border-bottom: 1px solid #FAEFDE;
        padding-bottom: 2rem;

        &:nth-last-child(1) {
          margin-top: 2rem;
        }

        .base {
          height: 4rem;
          width: 4rem;
          border-radius: 50%;
          text-align: center;
          line-height: 4rem;
          font-size: 2.3rem;
          font-family: baloo;
        }

        >.title {
          @include fontStyle(1.4);
          margin-bottom: 1rem;
        }

        >.content {
          display: grid;
          grid-template-columns: repeat(5, 1fr);
          grid-gap: 1.8rem;
        }
      }
    }
  }
}
</style>
<style module="status">
.info {
  background-color: #E9E9E9;
  color: #C4C4C4;
}

.success {
  background-color: #ECF3D2;
  color: #9AA435;
}

.error {
  background-color: #FFE6E6;
  color: #EC6357;
}
</style>
